package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.common.constant.ProductConstant;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.service.ProductAttrValueService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        // 添加关联关系
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            // 注意，attrVo 不包含 attrId ，但是 AttrEntity 保存之后就携带了 attrId
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(relationEntity);
        }
    }


    @Override
    public PageUtils findAttrList(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);

        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and((item) -> {
                item.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        // 我们需要关联表的意义就是避免连表查询，当连表查询时，笛卡尔积 1000 * 10000 = 10000000 ,会压垮数据库
        // 1. 创建AttrRespVo
        // 2. 通过关联表查询我们需要的数据
        List<AttrEntity> records = page.getRecords();

        // 循环得到需要数据
        List<AttrRespVo> respVoList = records.stream().map(item -> {
            AttrRespVo respVo = new AttrRespVo();
            BeanUtils.copyProperties(item, respVo);
            // 查询对象得到 AttrGroup 对象

            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    // 保存 AttrgroupName
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            // 保存 CatelogName
            CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
            respVo.setCatelogName(categoryEntity.getName());
            return respVo;
        }).collect(Collectors.toList());


        PageUtils pageUtils = new PageUtils(page);
        // 将数据保存到响应数据中
        pageUtils.setList(respVoList);
        return pageUtils;
    }

    // 根据 attrId 得到 AttrVo 对象
    @Override
    public AttrRespVo getAttrVo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 得到 groupName
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId)
            );
            if (relationEntity != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 得到分类名
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        // 得到路径
        Long[] path = categoryService.findAttrGroupPath(categoryEntity.getCatId());
        attrRespVo.setCatelogPath(path);

        return attrRespVo;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void updateAttr(AttrVo attrVo) {
        // 1. 修改 Attr 的数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        // 2. 修改 Attr 与 AttrGroup 之间的关联关系
        // 只有是基本属性的时候才需要添加关联关系
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            // 我们需要判断 attr 是否存在 AttrGroup 中，所有可能是 新增或修改操作
            attrAttrgroupRelationService.saveOrUpdate(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        }
    }

    /**
     * 通过 attrGroupId 得到所有 attr 对象
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getAttrListByGroupId(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> list = attrgroupRelationEntityList.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        List<AttrEntity> attrList = this.list(new QueryWrapper<AttrEntity>().in("attr_id", list));
        return attrList;
    }

    @Override
    public List<ProductAttrValueEntity> listforSpu(Long spuId) {
        List<ProductAttrValueEntity> data = productAttrValueService.listforSpu(spuId);
        return data;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        // 编写sql语句只需要查询一次数据库
        return baseMapper.selectSearchAttrIds(attrIds);
    }

}